package com.lanou.musicproject.musicservice;


import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.musicproject.activity.MainActivity;
import com.lanou.musicproject.activity.MusicPlayActivity;
import com.lanou.musicproject.base.BaseApplication;
import com.lanou.musicproject.bean.MyMusicList;
import com.lanou.musicproject.bean.MySong;
import com.lanou.musicproject.bean.RankShowLink;
import com.lanou.musicproject.event.MyEvent;
import com.lanou.musicproject.lrc.LyricDownloadManager;
import com.lanou.musicproject.lrc.LyricLoadHelper;
import com.lanou.musicproject.lrcsc.LyricDownloadManagersrc;
import com.lanou.musicproject.lrcsc.LyricLoadHelpersrc;
import com.lanou.musicproject.suspendservice.FxService;
import com.lanou.musicproject.volley.VolleySingleton;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by lidong on 10.28
 */
public class MusicService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener {

    MediaPlayer player;
    private boolean isService = false;
    private Timer timer;
    boolean prepared = false;
    private VolleySingleton singleton;
    private String name;
    private String singer, lrcdownload;
    private String player_singer_image;
    private String url;
    private ArrayList<MyMusicList> musicLists;
    private int index;
    private List<MySong> locallist;

    public static int PLAYMODE;
    public static final int PLAYONLINE = 1;
    public static final int PLAYLOCAL = 0;

    public static final int RANDOM = 2;
    public static final int INORDER = 3;
    public static final int SINGLE = 4;
    public static int REPEATMODE = INORDER;
    public static RankShowLink link;
    private LyricLoadHelper mLyricLoadHelper;
    private boolean mIsLyricDownloading;
    private LyricLoadHelpersrc mLyricLoadHelpersrc;
    private LyricDownloadManager lyricDownloadManager;
    private LyricDownloadManagersrc lyricDownloadManagersrc;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicController();
    }


    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        lyricDownloadManager = new LyricDownloadManager();
        lyricDownloadManagersrc = new LyricDownloadManagersrc();
        mLyricLoadHelper = new LyricLoadHelper();

        singleton = VolleySingleton.getInstance(this);
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.setOnBufferingUpdateListener(this);
        EventBus.getDefault().register(this);

    }

    private void loadLyricByHand(String musicName, String url) {
        // 取得歌曲同目录下的歌词文件绝对路径
        lrcdownload = LyricDownloadManager.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lrcdownload);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            Log.i("", "loadLyric()--->本地有歌词，直接读取");
            mLyricLoadHelper.loadLyric(getLrcdownload());
            try {
                MusicPlayActivity.getHelpter().loadLyric(getLrcdownload());
            } catch (Exception e) {
            }
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            Log.i("", "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTask().execute(musicName, url);

        }
    }
    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地

            lrcdownload = lyricDownloadManager.fetchLyricContent(
                    params[0], params[1]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;

            return lrcdownload;

        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("", "网络获取歌词完毕，歌词保存路径:" + result);
            try {
                MusicPlayActivity.getHelpter().loadLyric(getLrcdownload());
            } catch (Exception e) {
            }
        }
    }


    private void loadLyricByHands(String musicName, String url) {
        // 取得歌曲同目录下的歌词文件绝对路径
        lrcdownload = BaseApplication.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lrcdownload);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            Log.i("", "loadLyric()--->本地有歌词，直接读取");
            try {
                MusicPlayActivity.getHelpers().loadLyric(getLrcdownload());
            } catch (Exception e) {
            }
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            Log.i("", "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTasks().execute(musicName, url);

        }
    }


    class LyricDownloadAsyncTasks extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            lrcdownload = lyricDownloadManagersrc.searchLyricFromWeb(
                    params[0], params[1]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;

            return lrcdownload;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("", "网络获取歌词完毕，歌词保存路径:" + result);
            try {
                MusicPlayActivity.getHelpers().loadLyric(getLrcdownload());
            } catch (Exception e) {
            }
        }
    }


    public void onEvent(MyEvent.PlayEvent playEvent) {
        switch (playEvent.getWhat()) {
            case PLAYLOCAL:
                PLAYMODE = PLAYLOCAL;
                Log.i("--playmode--", PLAYLOCAL + "");
                break;
            case PLAYONLINE:
                PLAYMODE = PLAYONLINE;
                Log.i("--playmode--", PLAYONLINE + "");
                break;
            case RANDOM:
                REPEATMODE = RANDOM;
                Log.i("--repeatmode--", RANDOM + "");
                break;
            case INORDER:
                REPEATMODE = INORDER;
                Log.i("--repeatmode--", INORDER + "");
                break;
            case SINGLE:
                REPEATMODE = SINGLE;
                Log.i("--repeatmode--", SINGLE + "");
                break;
        }
    }


    @Override
    public void onCompletion(MediaPlayer mp) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (PLAYMODE == PLAYONLINE) {
            //播放网络音乐时
            next();
            Log.i("next", "1111-------------");
        } else if (PLAYMODE == PLAYLOCAL) {
            //播放本地音乐时
            localNext();
            Log.i("localnext", "1111-------------");
        }
    }

    @Override

    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        player.start();
        addTimer();
        prepared = true;

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    class MusicController extends Binder implements MusicInterface {

        @Override
        public void play(ArrayList<MyMusicList> lists, int position) {

            musicLists = lists;
            index = position;
            MusicService.this.play(lists, position);
        }

        public void playLocal(List<MySong> mysong, int position) {
            locallist = mysong;
            index = position;
            MusicService.this.playLocal(mysong, position);
        }

        @Override
        public void pause() {
            MusicService.this.pause();
        }

        @Override
        public void continuePlay() {
            MusicService.this.continuePlay();
        }

        @Override
        public void seekTo(int progress) {
            MusicService.this.seekTo(progress);

        }

        @Override
        public boolean getIsPlay() {
            return MusicService.this.getIsPlay();
        }

        public ArrayList<MyMusicList> musicLists() {
            return musicLists;
        }

        @Override
        public int getDuration() {
            return MusicService.this.getDuration();
        }

        @Override
        public int getProgress() {
            return MusicService.this.getProgress();
        }

        @Override
        public String getName() {
            return MusicService.this.getName();
        }

        @Override
        public String getSinger() {
            return MusicService.this.getSinger();
        }

        @Override
        public String getlrcdownload() {
            return MusicService.this.getLrcdownload();
        }


        @Override
        public String getPlayer_Singer_Image() {
            return MusicService.this.getPlayer_singer_image();
        }

        @Override
        public String url() {
            return MusicService.this.getUrl();
        }

        @Override
        public void next() {
            MusicService.this.next();
        }

        @Override
        public void localNext() {
            MusicService.this.localNext();
        }

        @Override
        public void former() {
            MusicService.this.former();
        }

        @Override
        public void localFormer() {
            MusicService.this.localFormer();
        }

        @Override
        public void playSingle() {
            MusicService.this.playSingle();
        }

    }

    //网络歌曲下一首
    public void next() {
        /**
         *
         * 判断随机播放
         *
         * */
        if (REPEATMODE == INORDER) {
            //顺序播放的下一首
            if (musicLists != null && musicLists.size() > 0) {
                if (index + 1 > musicLists.size() - 1) {
                    index = 0;
                } else {
                    index++;
                }
                play(musicLists, index);
                Log.i("next", "22222-------------");
            } else {
                Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
            }
        } else if (REPEATMODE == RANDOM) {
            //随机播放的下一首
            Random random = new Random();
            int indexRandom = random.nextInt(musicLists.size());
            play(musicLists, indexRandom);
        } else if (REPEATMODE == SINGLE) {
            play(musicLists, index);
        }

    }

    public void localNext() {
        if (REPEATMODE == INORDER) {
            if (locallist != null && locallist.size() > 0) {

                Log.i("--next--", "11111111111111111111");
                if (index + 1 > locallist.size() - 1) {
                    index = 0;
                } else {
                    index++;
                }
                playLocal(locallist, index);
                Log.i("localnext", "22222-------------");
            } else {
                Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
            }
        } else if (REPEATMODE == RANDOM) {
            //随机播放的下一首
            Random random = new Random();
            int indexRandom = random.nextInt(locallist.size());
            playLocal(locallist, indexRandom);
        } else if (REPEATMODE == SINGLE) {
            playLocal(locallist, index);
        }
    }

    //本地歌曲的上一首
    public void former() {

        if (musicLists != null && musicLists.size() > 0) {

            if (index < 1) {
                index = musicLists.size() - 1;
            } else {
                index--;
            }
            play(musicLists, index);
        } else {
            Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    public void localFormer() {
        if (locallist != null && locallist.size() > 0) {
            if (index < 1) {
                index = locallist.size() - 1;
            } else {
                index--;
            }
            playLocal(locallist, index);
        } else {
            Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    //播放在线音乐
    public void play(final ArrayList<MyMusicList> lists, final int position) {

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        name = lists.get(position).getName();
        singer = lists.get(position).getSinger();
        player_singer_image = lists.get(position).getPlayer_singer_image();

        //重置
        String song_id = lists.get(position).getSongId();
        if (song_id == null) {
            {
                String url = lists.get(position).getUrl();
                if (url != null) {
                    Log.i("----->>>", url + "");
                    loadLyricByHands(lists.get(position).getName(), lists.get(position).getSinger());
                    player.reset();
                    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        player.setDataSource(url);
                        player.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(MusicService.this, "此歌曲为空请选择下一首", Toast.LENGTH_LONG).show();
                }
            }

        } else {
            String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    song_id + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    String str = response.toString();
                    link = JSON.parseObject(str, RankShowLink.class);
                    if (link.getSongurl().getUrl().get(0).getShow_link() != null) {
                        //歌曲视听url
                        String url = link.getSongurl().getUrl().get(0).getShow_link();
                        /**
                         * 下载歌词
                         * */
                        loadLyricByHand(link.getSonginfo().getTitle(),
                                link.getSonginfo().getLrclink());
                        Log.i("Sysemy.out",link.getSonginfo().getLrclink());
                        player.reset();
                        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        //加载多媒体文件
                        try {
                            player.setDataSource(url);
                            player.prepareAsync();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            singleton.addQueue(jr, "MusicPlayer");

        }
    }

    //播放本地音乐
    public void playLocal(List<MySong> mysong, int position) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        name = mysong.get(position).getTitle();
        singer = mysong.get(position).getArtist();
        if (mysong.get(position).getAlbumCover() != null) {
            player_singer_image = mysong.get(position).getAlbumCover().toString();

        } else {
            Log.i("---image---", "null");

        }
        loadLyricByHands(mysong.get(position).getTitle(), mysong.get(position).getArtist());
        player.reset();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            player.setDataSource(mysong.get(position).getPath());
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.start();
    }

    /**
     * 单曲循环
     **/

    public void playSingle() {

    }

    public boolean getIsPlay() {
        return player.isPlaying();
    }

    //继续播放
    public void continuePlay() {
        player.start();
    }


    //暂停播放
    public void pause() {
        player.pause();
    }

    public void seekTo(int progress) {
        player.seekTo(progress);
    }


    public int getDuration() {
        int i = 0;
        if (prepared) {
            i = player.getDuration();
        }
        return i;
    }

    public int getProgress() {
        int i = 0;
        if (prepared) {
            i = player.getCurrentPosition();
        }
        return i;
    }

    public String getName() {
        return name;
    }

    public String getSinger() {
        return singer;
    }

    public String getLrcdownload() {
        return lrcdownload;
    }

    public String getPlayer_singer_image() {
        return player_singer_image;
    }

    public ArrayList<MyMusicList> musicLists() {
        return musicLists;
    }

    public String getUrl() {
        return url;
    }

    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    //获取歌曲总时长
                    int duration = player.getDuration();
                    //获取歌曲当前播放进度
                    int currentPosition = player.getCurrentPosition();
                    Message msg = MainActivity.handler.obtainMessage();
                    Message msgfx = FxService.handler.obtainMessage();
                    Message msgplay = MusicPlayActivity.handler.obtainMessage();

                    //把进度封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    msg.setData(bundle);
                    msgfx.setData(bundle);
                    msgplay.setData(bundle);
                    MainActivity.handler.sendMessage(msg);
                    FxService.handler.sendMessage(msgfx);
                    MusicPlayActivity.handler.sendMessage(msgplay);

                }
                //开始计时任务后的5毫秒，第一次执行run方法，以后每500毫秒执行一次
            }, 0, 500);
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //释放占用的资源，此时player对象已经废掉了
        player.release();
        player = null;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }


        EventBus.getDefault().unregister(this);
    }

    public boolean IsService(Context mContext, String serviceName) {
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals("com.lanou.musicproject.suspendservice.FxService")) {
                isService = true;
                break;
            }
        }
        return isService;

    }
}

